from typing import Dict, Any, List
from .base_agent import BaseAgent, AgentResult
from datetime import datetime
import logging
import json

class PublishAgent(BaseAgent):
    """内容发布智能体 - 负责将生成的文案发布到各个平台"""
    
    def __init__(self, config_path: str = None):
        super().__init__()
        self.config_path = config_path
        self.name = "PublishAgent"
        self.version = "1.0.0"
        self.logger = logging.getLogger(self.__class__.__name__)
        # 初始化平台发布客户端（实际项目中应替换为真实的API客户端）
        self.platform_clients = self._init_platform_clients()
    
    def get_name(self) -> str:
        return self.name
    
    def get_version(self) -> str:
        return self.version
    
    def get_dependencies(self) -> List[str]:
        """依赖CopywritingGenerationAgent生成的文案"""
        return ["CopywritingGenerationAgent"]
    
    def execute(self, input_data: Dict[str, Any]) -> AgentResult:
        """执行发布任务"""
        self.log_execution_start()
        start_time = datetime.now()
        
        try:
            # 验证输入
            if not self.validate_input(input_data):
                execution_time = (datetime.now() - start_time).total_seconds()
                self.log_execution_end(False, execution_time)
                return AgentResult(
                    success=False,
                    data={},
                    error="输入数据验证失败"
                )
            
            # 获取需要发布的平台列表
            platforms_to_publish = input_data.get("platforms_to_publish", [])
            if not platforms_to_publish:
                # 默认发布到所有可用平台
                platforms_to_publish = ["weibo", "douyin", "wechat"]
            
            # 从CopywritingGenerationAgent结果中获取文案
            copywriting_result = input_data.get("CopywritingGenerationAgent_result", {})
            if not copywriting_result:
                # 尝试直接从input_data中获取文案
                copywriting_result = input_data.get("copywriting_data", {})
            
            if not copywriting_result:
                execution_time = (datetime.now() - start_time).total_seconds()
                self.log_execution_end(False, execution_time)
                return AgentResult(
                    success=False,
                    data={},
                    error="未找到可发布的文案内容"
                )
            
            # 执行发布操作
            publish_results = self._publish_to_platforms(copywriting_result, platforms_to_publish)
            
            execution_time = (datetime.now() - start_time).total_seconds()
            self.log_execution_end(True, execution_time)
            
            return AgentResult(
                success=True,
                data=publish_results,
                metadata={
                    "platforms_published": platforms_to_publish,
                    "execution_time": execution_time,
                    "timestamp": datetime.now().isoformat()
                }
            )
            
        except Exception as e:
            execution_time = (datetime.now() - start_time).total_seconds()
            self.log_execution_end(False, execution_time)
            self.logger.error(f"发布过程发生错误: {str(e)}")
            return AgentResult(
                success=False,
                data={},
                error=f"发布失败: {str(e)}"
            )
    
    def validate_input(self, input_data: Dict[str, Any]) -> bool:
        """验证输入数据"""
        # 检查是否有CopywritingGenerationAgent的结果或直接的文案数据
        has_copywriting_result = "CopywritingGenerationAgent_result" in input_data and input_data["CopywritingGenerationAgent_result"]
        has_direct_copywriting = "copywriting_data" in input_data and input_data["copywriting_data"]
        
        return has_copywriting_result or has_direct_copywriting
    
    def _init_platform_clients(self) -> Dict[str, Any]:
        """初始化各平台的发布客户端
        实际项目中，这里应该初始化各个平台的API客户端实例
        """
        # 这里使用模拟客户端，实际实现时应替换为真实的API客户端
        return {
            "weibo": self._create_weibo_client(),
            "douyin": self._create_douyin_client(),
            "wechat": self._create_wechat_client()
        }
    
    def _create_weibo_client(self) -> Any:
        """创建微博发布客户端"""
        # 模拟微博客户端，实际实现时应使用微博开放平台SDK
        return {
            "name": "WeiboClient",
            "version": "1.0.0",
            "config": {"api_base_url": "https://api.weibo.com"}
        }
    
    def _create_douyin_client(self) -> Any:
        """创建抖音发布客户端"""
        # 模拟抖音客户端，实际实现时应使用抖音开放平台SDK
        return {
            "name": "DouyinClient",
            "version": "1.0.0",
            "config": {"api_base_url": "https://open.douyin.com"}
        }
    
    def _create_wechat_client(self) -> Any:
        """创建微信公众号发布客户端"""
        # 模拟微信客户端，实际实现时应使用微信公众号SDK
        return {
            "name": "WechatClient",
            "version": "1.0.0",
            "config": {"api_base_url": "https://api.weixin.qq.com"}
        }
    
    def _publish_to_platforms(self, copywriting_data: Dict[str, Any], platforms: List[str]) -> Dict[str, Dict[str, Any]]:
        """将文案发布到指定平台"""
        results = {}
        
        for platform in platforms:
            if platform not in copywriting_data:
                results[platform] = {
                    "success": False,
                    "error": f"未找到平台 '{platform}' 的文案内容"
                }
                continue
            
            try:
                if platform == "weibo":
                    results[platform] = self._publish_to_weibo(copywriting_data[platform])
                elif platform == "douyin":
                    results[platform] = self._publish_to_douyin(copywriting_data[platform])
                elif platform == "wechat":
                    results[platform] = self._publish_to_wechat(copywriting_data[platform])
                else:
                    results[platform] = {
                        "success": False,
                        "error": f"不支持的平台 '{platform}'"
                    }
            except Exception as e:
                results[platform] = {
                    "success": False,
                    "error": f"发布失败: {str(e)}"
                }
        
        return results
    
    def _publish_to_weibo(self, content_data: Dict[str, Any]) -> Dict[str, Any]:
        """发布内容到微博"""
        # 实际项目中，这里应调用微博开放平台API
        content = content_data.get("content", "")
        hashtags = content_data.get("hashtags", [])
        
        # 模拟发布过程
        post_content = f"{content}\n\n{' '.join(hashtags)}"
        
        # 记录发布日志
        self.logger.info(f"模拟发布到微博: {post_content[:50]}...")
        
        # 模拟成功响应
        return {
            "success": True,
            "post_id": f"weibo_{datetime.now().timestamp()}",
            "published_at": datetime.now().isoformat(),
            "content": post_content,
            "message": "发布成功"
        }
    
    def _publish_to_douyin(self, content_data: Dict[str, Any]) -> Dict[str, Any]:
        """发布内容到抖音"""
        # 实际项目中，这里应调用抖音开放平台API
        content = content_data.get("content", "")
        video_script = content_data.get("video_script", "")
        
        # 模拟发布过程
        self.logger.info(f"模拟发布到抖音: {content[:50]}...")
        
        # 模拟成功响应
        return {
            "success": True,
            "video_id": f"douyin_{datetime.now().timestamp()}",
            "published_at": datetime.now().isoformat(),
            "content": content,
            "has_video_script": bool(video_script),
            "message": "发布成功"
        }
    
    def _publish_to_wechat(self, content_data: Dict[str, Any]) -> Dict[str, Any]:
        """发布内容到微信公众号"""
        # 实际项目中，这里应调用微信公众号API
        content = content_data.get("content", "")
        
        # 模拟发布过程
        self.logger.info(f"模拟发布到微信公众号: {content[:50]}...")
        
        # 模拟成功响应
        return {
            "success": True,
            "article_id": f"wechat_{datetime.now().timestamp()}",
            "published_at": datetime.now().isoformat(),
            "content_preview": content[:100],
            "message": "发布成功"
        }